package cn.xiaolang.rest.remote;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

@Slf4j
public class RestClientUtil {

    private static final RestTemplate restTemplate = new RestTemplate();

    public static <R> R execute(RestApiRequest requestDetails, Object data, Class<R> responseType) {
        HttpHeaders headers = requestDetails.getHttpHeaders();
        HttpEntity<Object> entity = new HttpEntity<>(data, headers);
        log.info("remote_request: req={}", requestDetails);
        ResponseEntity<R> response = null;
        try {
            response = restTemplate.exchange(requestDetails.getEndPointUri(), requestDetails.getHttpMethod(),
                    entity, responseType);
            R respBody = response.getBody();
            log.info("remote_request: req={},resp={}", requestDetails, respBody);
            return respBody;
        } catch (RestClientException e) {
            log.error("remote_request: req={},exception:", requestDetails, e);
        }
        return null;
    }
}
